package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override//把文件中的内容保存在数据库中
    public void add(List<OrderSetting> data) {
        //根据传递的参数的日期来判断增加或修改数据库中的数据
        if (data != null && data.size() > 0) {
            for (OrderSetting orderSetting : data) {
                long count = orderSettingDao.findCountByDate(orderSetting.getOrderDate());
                if (count > 0) {
                    orderSettingDao.editNumberByDate(orderSetting);
                } else orderSettingDao.add(orderSetting);
            }
        }
    }

    @Override
    public List<Map> getOrderSettingByMonth(String date) {//页面传递的日期格式为-
        //Dao层查找一个月的数据返回，页面中的date属性是String，orderSEtting中的date属性是Date
        //所以使用map进行封装，返回页面需要的元素
        String beginDate = date + "-1";
        String endDate = date + "-31";
        Map<String, String> map = new HashMap<>();
        map.put("beginDate", beginDate);
        map.put("endDate", endDate);
        //根据map查找信息
        List<OrderSetting> orderSettingByMonth = orderSettingDao.getOrderSettingByMonth(map);
        //把信息按照页面要求封装在map中发送
        List<Map> result = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettingByMonth) {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("date", orderSetting.getOrderDate().getDate());
            map1.put("number", orderSetting.getNumber());
            map1.put("reservations", orderSetting.getReservations());
            result.add(map1);
        }
        return result;
    }

    @Override
    public void edit(OrderSetting orderSetting) {
        Date orderDate = orderSetting.getOrderDate();
        //通过点击页面上的设置也可以网数据库添加信息
        long count = orderSettingDao.findCountByDate(orderDate);
        if (count > 0) orderSettingDao.editNumberByDate(orderSetting);
        else orderSettingDao.add(orderSetting);
    }
}
